// src/websocket.js
let socket;

export function connectWebSocket(userId, receiverId, onMessageCallback) {
  // 更新 URL 路径为 /chat/ws
  const url = `ws://localhost:8888/chat/ws?user_id=${userId}&receiver_id=${receiverId}`;
  socket = new WebSocket(url);

  socket.onopen = () => {
    console.log("WebSocket connected");
  };

  socket.onmessage = (event) => {
    const message = JSON.parse(event.data);
    onMessageCallback(message);
  };

  socket.onclose = () => {
    console.log("WebSocket closed");
  };

  socket.onerror = (error) => {
    console.error("WebSocket error:", error);
  };
}

export function sendMessage(content) {
  if (socket && socket.readyState === WebSocket.OPEN) {
    socket.send(content);
  } else {
    console.error("WebSocket is not connected");
  }
}

export function closeWebSocket() {
  if (socket) {
    socket.close();
  }
}
